package com.management.department.teacherinfosystem.Repository;


import com.management.department.teacherinfosystem.Entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
    User findByName(String name);
    // UserRepository.java
    boolean existsByUsername(String username);
    Optional<User> findByUsername(String username);
    Optional<User> findByStaffNo(String staffNo);

    // 查询用户并立即加载角色信息
    @Query("SELECT u FROM User u LEFT JOIN FETCH u.userRoles ur LEFT JOIN FETCH ur.role WHERE u.username = :username")
    Optional<User> findByUsernameWithRoles(@Param("username") String username);
    
    // 根据ID查询用户并立即加载角色信息
    @Query("SELECT u FROM User u LEFT JOIN FETCH u.userRoles ur LEFT JOIN FETCH ur.role WHERE u.id = :id")
    Optional<User> findByIdWithRoles(@Param("id") Long id);
    
    // 分页查询所有用户并预加载角色信息
    @Query(value = "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.userRoles ur LEFT JOIN FETCH ur.role",
           countQuery = "SELECT COUNT(DISTINCT u) FROM User u")
    Page<User> findAllWithRoles(Pageable pageable);

}
